var elements=[];
var curElement="";

$(document).ready(function(e) {
    init();
    $('.layer-before-canvas').click(addElement);
    $("#pointer").click(clickMouse);
    $("#addText").click(clickText);
    $("#addImage").click(clickImage);
    $("#eraser").click(clickEraser);
    $("#exportPdf").click(exportPdf);
    
    $("#format-bold").click(setFontBold);
    $("#format-italic").click(setFontItalic);
    $("#format-underline").click(setFontUnderline);
    $("#format-strikethrough").click(setFontStrike);
});

function setFontBold(){
    var index = getElementIndex(curElement);
    if (elements[index]["type"] != 1)
        return;
    var value = elements[index]["fontBold"];
    if (value == 0)
        value = 1;
    else
        value = 0;
    elements[index]["fontBold"] = value;
    setElementStyle(curElement);
}
function setFontItalic(){
    var index = getElementIndex(curElement);
    if (elements[index]["type"] != 1)
        return;
    var value = elements[index]["fontItalic"];
    if (value == 0)
        value = 1;
    else
        value = 0;
    elements[index]["fontItalic"] = value;
    setElementStyle(curElement);
}
function setFontUnderline(){
    var index = getElementIndex(curElement);
    if (elements[index]["type"] != 1)
        return;
    var value = elements[index]["fontUnderline"];
    if (value == 0)
        value = 1;
    else
        value = 0;
    elements[index]["fontUnderline"] = value;
    setElementStyle(curElement);
}
function setFontStrike(){
    var index = getElementIndex(curElement);
    if (elements[index]["type"] != 1)
        return;
    var value = elements[index]["fontStrike"];
    if (value == 0)
        value = 1;
    else
        value = 0;
    elements[index]["fontStrike"] = value;
    setElementStyle(curElement);
}

function exportPdf() {
    var seri;
    for (var i = 0; i < elements.length; i++) {
        var object = elements[i];
        for (property in object) {
            var value = object[property];
            seri += property + "=" + value + "&";
        }
    }
    alert(seri);
    $.ajax({
        type:           'post',
        cache:          false,
        url:            'export.php?code=' + $("#code").val(),
        data:           seri,
        success: function(d){
            alert(d);
        }
    });
//$.download('export.php?code=' + $("#code").val() ,seri);
//blockUIForDownload();
}

jQuery.download = function(url, data, method){
    if( url && data ){
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        jQuery.each(data.split('&'), function(){
            var pair = this.split('=');
            inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
        });
        jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
        .appendTo('body').submit().remove();
    };
};

var fileDownloadCheckTimer;
function blockUIForDownload() {
    var token = new Date().getTime();
    $('#download_token_value_id').val(token);
    $.blockUI();
    fileDownloadCheckTimer = window.setInterval(function () {
        var cookieValue = $.cookie('fileDownloadToken');
        if (cookieValue == token)
            finishDownload();
    }, 1000);
}
function finishDownload() {
    window.clearInterval(fileDownloadCheckTimer);
    $.cookie('fileDownloadToken', null);
    $.unblockUI();
}


////////////////////////////////////////////////////////////////////////////////
///////////////////////ELEMENTS
////////////////////////////////////////////////////////////////////////////////

/**
 * Loại đối tượng:
 * 0: không thêm đối tượng.
 * 1: thêm đối tượng văn bản.
 * 2: thêm đối tượng hình ảnh.
 * 3: thêm đối tượng tẩy xóa (cho dữ liệu cũ đã có trên pdf).
 */
var elementType=0;
var countElements = 0;      //Đếm số đối tượng đã thêm (văn bản+hình ảnh+tẩy xóa).
var countTextElements = 0;  //Đếm số đối tượng văn bản đã thêm.
var countImageElements = 0; //Đếm số đối tượng hình ảnh đã thêm.
var countEraseElements = 0; //Đếm số đối tượng tẩy xóa đã thêm.

function init() {
    alert("Nội dung pdf đã được tải thành công." + $('#canvas-0').serialize());
}

function addElement(e) {
    //Add element id to selector with id "objects".
    var posLeft = Math.round(e.pageX - $(this).offset().left);
    var posTop = Math.round(e.pageY - $(this).offset().top);
    var element;
    var idLayer = e.target.id;
    var parts = idLayer.split("-");
    var page = parts[3];
    switch (elementType) {
        case 0:
            focusOn(e.target.id);
            break;
        case 1:
            element = document.createElement("div");
            element.id="text"+countTextElements++ + "-" + page;
            var place = this;
            $("#inputDialog").dialog({
                height: 230,
                width: 350,
                modal: true,
                open: function() {
                    $("#inputText").val("v\u0103n bản mặc định");
                },
                buttons: {
                    "Thêm": function() {
                        element.innerHTML = $("#inputText").val();
                        element.className = "textElement";
                        element.setAttribute("style", "position:absolute;left:"+posLeft+"px;top:"+posTop+"px;z-index:"+countElements++ + ";");
                        $(element).draggable({
                            containment:'parent',
                            cursor: 'move'
                        });
                        $(element).resizable();
                        place.appendChild(element);
                        addObjectToList(element.id, 1);
                        $(this).dialog("close");
                    }
                }
            });
            break;
        case 2:
            element = new Image();
            element.id="image"+countImageElements++ + "-" + page;
            element.className = "imageElement";
            $("#uploadDialog").dialog({
                height: 220,
                width: 420,
                modal: true,
                open: function() {
                    $("#fileToUpload").val("");
                },
                buttons: {
                    "Tải lên": function() {
                        $("#loading").ajaxStart(function() {
                            $(this).show();
                        }).ajaxComplete(function(){
                            $(this).hide();
                        });
                        $.ajaxFileUpload({
                            url:'uploadimage.php',
                            secureuri:false,
                            fileElementId:'fileToUpload',
                            dataType: 'json',
                            data:{
                                name:'logan', 
                                id:'id'
                            },
                            success: function (data, status) {
                                if(typeof(data.error) != 'undefined') {
                                    if(data.error != '') {
                                        alert(data.error);
                                    } else {
                                        $("#uploadDialog").dialog("close");
                                        alert(data.msg);
                                        element.src = data.imageUrl;
                                    }
                                }
                            },
                            error: function (data, status, e) {
                                $("#uploadDialog").dialog("close");
                                alert(e);
                            }
                        })
                        return false;
                    }
                }
            });
            element.setAttribute("style", "position:absolute;left:"+posLeft+"px;top:"+posTop+"px;z-index:"+countElements++ + ";");
            this.appendChild(element);
            $(element).resizable().parent().draggable({
                containment:'parent',
                cursor: 'move'
            });
            var draggable = $(element).resizable().parent().draggable( "option", "disabled" );
            var resizable = $(element).resizable( "option", "disabled" );
            addObjectToList(element.id, 2);
            break;
        case 3:
            element = document.createElement("div");
            element.id="erase"+countEraseElements++ + "-" + page;
            element.className = "eraseElement";
            element.setAttribute("style", "position:absolute;left:"+posLeft+"px;top:"+posTop+"px;width: 200px; height: 100px; background: white;z-index:"+ countElements++ + ";");
            $(element).draggable({
                containment:'parent',
                cursor: 'move'
            });
            $(element).resizable();
            this.appendChild(element);
            var drag = $(element).draggable( "option", "disabled" );
            var resize = $(element).resizable( "option", "disabled" );
            addObjectToList(element.id, 3);
            break;
    }
    clickMouse();
}

function focusOn(id) {
    var eId = "#"+id;
    $("*").removeClass("focusOn");
    curElement="";
    if ($(eId).attr("class") != "layer-before-canvas") {
        $(eId).addClass("focusOn");
        curElement=$(eId).attr("id");
    }
    $("*").removeClass("li_focus");
    $("#li_"+ id).attr("class", "li_focus");
}

function clickMouse() {
    elementType=0;
    $('.layer-before-canvas').css('cursor', 'default');
}
function clickText() {
    elementType=1;
    $('.layer-before-canvas').css('cursor', 'url("./style/icons/draw-text-2.png"),auto');
}
function clickImage() {
    elementType=2;
    $('.layer-before-canvas').css('cursor', 'url("./style/icons/kgpg_photo.png"),auto');
}
function clickEraser() {
    elementType=3;
    $('.layer-before-canvas').css('cursor', 'url("./style/icons/draw-rectangle-2.png"),auto');
}

function addObjectToList(id, type) {
    $("#objectlist").append("<li id='li_"+ id +"' onclick='focusOn(\""+id+"\");'>"
        +"<a class='name' href='#"+id+"'>" + id + "</a>"
        +"<div class='remove' onclick='removeId(\"" + id + "\");'></div></li>");
    elements.push(id);
    var theLastElementIndex = elements.length-1;
    elements[theLastElementIndex] = new Array(12);
    elements[theLastElementIndex]['id'] = id;
    elements[theLastElementIndex]['type'] = type;
    if (type == 1) {
        elements[theLastElementIndex]['text'] = $("#"+id).val();
    } else if (type==2) {
        elements[theLastElementIndex]['text'] = $("#"+id).attr("src");
    } else
        elements[theLastElementIndex]['text'] = "";
    elements[theLastElementIndex]['fontName'] = $("#"+id).css("font-family");
    elements[theLastElementIndex]['fontSize'] = $("#"+id).css("font-size");
    elements[theLastElementIndex]['fontBold'] = 0;
    elements[theLastElementIndex]['fontItalic'] = 0;
    elements[theLastElementIndex]['fontUnderline'] = 0;
    elements[theLastElementIndex]['fontStrike'] = 0;
    elements[theLastElementIndex]['height'] = $("#"+id).css("height");
    elements[theLastElementIndex]['width'] = $("#"+id).css("width");
    elements[theLastElementIndex]['color'] = $("#"+id).css("color");

}

function removeId(id) {
    $("#"+id).remove();
    $("#li_"+id).remove();
}

function getElementIndex(id) {
    for (i=0;i< elements.length;i++)
        if (elements[i]['id'] == id)
            return i;
    return -1;
}

function setElementStyle(id) {
    var index = getElementIndex(id);
    var elementId = "#"+id;
    $(elementId).css("font-family", elements[index]['fontName']);
    $(elementId).css("font-size", elements[index]['fontSize']);
    if (elements[index]['fontBold'] == 0)
        $(elementId).css("font-weight", "normal");
    else if (elements[index]['fontBold'] == 1)
        $(elementId).css("font-weight", "bold");
    
    if (elements[index]['fontItalic'] == 0)
        $(elementId).css("font-style", "normal");
    else if (elements[index]['fontItalic'] == 1)
        $(elementId).css("font-style", "italic");
    
    var decoration = "";
    if (elements[index]['fontUnderline'] == 1)
        decoration += " underline ";
    if (elements[index]['fontUnderline'] == 1)
        decoration += " line-through ";
    if (decoration == "")
        decoration = "normal";
    $(elementId).css("text-decoration", decoration);
    updateElementHeightWidth(elementId);
    $(elementId).css("height", elements[index]['height']);
    $(elementId).css("width", elements[index]['width']);
    $(elementId).css("color", elements[index]['color']);
}
function updateElementHeightWidth(id) {
    var index = getElementIndex(id);
    elements[index]['height'] = $(id).css("height");
    elements[index]['width'] = $(id).css("width");
}